﻿using Consul;
using Microsoft.Extensions.Options;

namespace order.Config
{
    public class ServiceDiscoveryHostedService : IHostedService
    {
        private readonly IConsulClient _client;
        private readonly ConsulRegisterOptions _config;
        private string _registrationId;

        public ServiceDiscoveryHostedService(IConsulClient client, ConsulRegisterOptions config)
        {
            _client = client;
            _config = config;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {

            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                HTTP = $"http://{_config.ServiceAddress.Host}:{_config.ServiceAddress.Port}/api/health",//健康检查地址
                Timeout = TimeSpan.FromSeconds(5)
            };

            _registrationId = $"{_config.ServiceName}-{Guid.NewGuid().ToString()}";

            var registration = new AgentServiceRegistration
            {
                Checks = new[] { httpCheck },
                ID = _registrationId,
                Name = _config.ServiceName,
                Address = _config.ServiceAddress.Host,
                Port = _config.ServiceAddress.Port
            };

            await _client.Agent.ServiceDeregister(registration.ID, cancellationToken);
            await _client.Agent.ServiceRegister(registration, cancellationToken);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _client.Agent.ServiceDeregister(_registrationId, cancellationToken);
        }
    }
}
